import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CSVReader {
	private char spilter = ',';
	private String path;
	private File file = null;
	private FileReader fileReader = null;
	private BufferedReader br = null;
	
	public CSVReader(String path){
		this.path = path;
		try {
			file = new File(this.path);
			fileReader = new FileReader(file);
			br = new BufferedReader(fileReader);
		} catch (FileNotFoundException e) {
			System.out.println("File not found on:"+path);
			e.printStackTrace();
		}
	}
	
	public CSVReader(char spilter,String path){
		this(path);
		this.spilter = spilter;
	}
	
	
	public List<String> readOneRow(){
		try {
			String s = br.readLine();
			if(s == null){
				//读到文件末尾，关闭文件
				close();
				return null;
			}
			//不适用split函数，自己处理，因为存在双引号的问题
			List<String> ret = new ArrayList<String>();
			int qoutationCnt = 0;
			int beginIndex = 0;
			int i;
			for(i = 0;i < s.length(); i++){
				
				if(s.charAt(i) == spilter && qoutationCnt % 2 == 0){
					String tmps = s.substring(beginIndex,i);
					//去掉两侧的双引号
					if(tmps.startsWith("\"") && tmps.endsWith("\"")){
						tmps = tmps.substring(1, tmps.length()-1);
					}
					ret.add(tmps);
					beginIndex = i+1;
					continue;
				}
				
				if(s.charAt(i) == '"'){
					qoutationCnt ++;
				}
			}
			//最后一部分要读进来
			if(beginIndex < i){
				String tmps = s.substring(beginIndex,i);
				//去掉两侧的双引号
				if(tmps.startsWith("\"") && tmps.endsWith("\"")){
					tmps = tmps.substring(1, tmps.length()-1);
				}
				ret.add(tmps);
			}
			
//			return (String[]) ret.toArray(new String[ret.size()]);
			return ret;
			
		} catch (IOException e) {
			System.out.println("Exception in readOneRow");
			e.printStackTrace();
		}
		
		return null;
	}
	
	public void close(){
		try {
			br.close();
			fileReader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String args[]){
		CSVReader csvReader = new CSVReader(';', "bank-additional-full.csv");
		csvReader.readOneRow();
		System.out.println(csvReader.readOneRow());
		
		
		//检测最后几列数据是否都是一样的
//		csvReader.readOneRow();
//		
//		String preValue;
//		List<String> row;
//		preValue = csvReader.readOneRow().get(16);
//		for(int i = 0;(row = csvReader.readOneRow())!= null;i++){
//			String tmpV = row.get(16);
//			if(!tmpV.equals(preValue)){
//				System.out.println("false:"+preValue+"|"+tmpV+"|"+i);
//			}
//		}
//		System.out.println("True:"+preValue);
		
	}
	
}






























